import router, { addRouters } from '@/router'
import { backendMenus } from '@/router/menus/backend.menu'
import { doctorMenus } from '@/router/menus/doctor-menu'
import { userMenus } from '@/router/menus/user-menu'
import { Vue } from 'vue-property-decorator'
import global from './global'
const TOKEN_KEY = 'token'
const USERINFO_KEY = 'userinfo'

class UserManage {
  user = {} as any
  token: string | null = null

  setUserInfoAndToken(user: IUser) {
    sessionStorage.setJsonItem(USERINFO_KEY, user)
  }

  getToken() {
    return sessionStorage.getItem(TOKEN_KEY)
  }

  getUser(): IUser {
    return sessionStorage.getJsonItem(USERINFO_KEY)
  }

  handleLogin(vue: Vue, user: IUser): boolean {
    if (!user) {
      return false
    }

    // ++++++++++ 全局变量 +++++++++
    global.add('$User', user)

    let menus: Array<any> = []

    // ++++++++++ 路由 ++++++++++
    switch (user.type) {
      // 用户
      case 'user':
        menus = userMenus(undefined)
        break
      // 医生
      case 'doctor':
        menus = doctorMenus(user)
        break
      // 管理后台
      case 'admin':
        menus = backendMenus(user)
        break
    }
    addRouters(menus)
    vue.$router.push(menus[0].key)

    return true
  }

  handleExit() {
    const userinfo = this.getUser()

    sessionStorage.clear()
    if (userinfo.type == 'admin') {
      router.push('/backend/login')
    } else {
      router.push('/')
    }
    location.reload()
  }
}

const userManage = new UserManage()

export { userManage }
